package org.telegram.bot.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.system.service.ISysConfigService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.telegram.bot.domain.BotInfo;
import org.telegram.bot.emums.BotCommonEnums;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.bot.mq.producer.GroupCacheRefreshProducer;
import org.telegram.bot.service.*;
import org.telegram.bot.utils.BotCMDUtil;
import org.telegram.telegrambots.meta.api.methods.groupadministration.RestrictChatMember;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.ChatPermissions;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.chat.Chat;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardRow;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wyx
 * @Date: 2023/5/31 10:24
 */
@Service
public class CommandServiceImpl implements ICommandService, IBotSendMessage {

    @Resource
    private IBotProhibitedWordsService prohibitedWordsService;

    @Resource
    private IBotInfoService botInfoService;
    
    @Resource
    private IBotGroupService botGroupService;
    
    @Resource
    private IBotChatMemberService botChatMemberService;
    
    @Resource
    private ISysConfigService sysConfigService;
    
    @Resource
    private GroupCacheRefreshProducer groupCacheRefreshProducer;
    @Override
    public void handle(Update update, Long chatId, String botId) {
        String botName = getBotInfo(botId).getBotName();
        String atBot = "@"+botName;
        //主菜单
         if(update.hasMessage() && (BotCMDUtil.MAIN_MENU.contains(update.getMessage().getText()) || update.getMessage().getText().contains(atBot)) || update.getMessage().getText().contains(BotCMDUtil.CMD_BAN)){
             String text = update.getMessage().getText();
             if(BotCMDUtil.validCmd(text,BotCMDUtil.CMD_START,botName)){
                 if(BotCommonEnums.CHAT_TYPE_PRIVATE.equals(update.getMessage().getChat().getType())){
                     startPrivate(update.getMessage().getChat(),botId,null);
                 }else{
                     start(update.getMessage().getChat(),botId,null);
                 }
             }
             else if(BotCMDUtil.validCmd(text,BotCMDUtil.CMD_BLACKLIST,botName)){
                 //添加违禁词
                 addBlockList(update.getMessage().getChat(),botId,update.getMessage().getText());
             }else if(update.getMessage().getText().contains(BotCMDUtil.CMD_BAN)){
                banUser(update.getMessage(),botId,botName,update.getMessage().getText());
             }
        }
         //携带命令参数的
        else if(update.hasMessage() ){
            
            //是否删除发送者消息
            boolean deleteMsg = false;
            String text = update.getMessage().getText();
             SendMessage message = SendMessage.builder().chatId(chatId).text("").build();
             
             //个人模式不支持
             if(BotCommonEnums.CHAT_TYPE_PRIVATE.equals(update.getMessage().getChat().getType())){
                 message.setText(BotCMDUtil.PERMISSIONS_ERROR_CHAT_TYPE);
                 send(botId,message);
                 return;
             }
             //直接发送的命令
             if(text.contains(BotCMDUtil.CMD_BLACKLIST)){
                 //非管理员禁止只用
                 if(!botChatMemberService.isAdminValid(chatId,update.getMessage().getFrom())){
                     message.setText(BotCMDUtil.PERMISSIONS_NOT_ADMIN);
                     send(botId,message);
                     return;
                 }
                 message.setText(prohibitedWordsService.insertBotProhibitedWords(chatId,text));
                 send(botId,message,20L);
                 deleteMsg = true;
             }
             if(deleteMsg){
                 send(botId, DeleteMessage.builder().chatId(chatId).messageId(update.getMessage().getMessageId()).build());
             }
         }
    }
    
    /**
     * 禁言用户
     * @param msg
     * @param botId
     * @param text
     */
    private void banUser(Message msg, String botId, String botName, String text) {
        SendMessage message = SendMessage.builder().chatId(msg.getChatId()).text("").build();
        message.setReplyToMessageId(msg.getMessageId());
        if(msg.getReplyToMessage()==null){
            message.setText("添加格式如下：\n回复用户消息，输入 /ban");
            send(botId,message);
            return;
        }
        
        //非管理员禁止只用
        if(!botChatMemberService.isAdminValid(msg.getChatId(),msg.getFrom())){
            message.setText(BotCMDUtil.PERMISSIONS_NOT_ADMIN);
            send(botId,message);
            return;
        }
        
        //判断是否管理员
        if(botChatMemberService.isAdminValid(msg.getChatId(),msg.getReplyToMessage().getFrom())){
            message.setText(BotCMDUtil.PERMISSIONS_USER_IS_ADMIN);
            send(botId,message);
            return;
        }
        
        try {
            sendAsync(botId, RestrictChatMember.builder()
                    .chatId(msg.getChatId())
                    .userId(msg.getReplyToMessage().getFrom().getId())
                    .untilDate(0)
                    .permissions(ChatPermissions.builder().canSendMessages(false).build())
                    .build());
        }
        catch (ServiceException e){
            message.setText(e.getMessage());
            send(botId,message);
            throw e;
        }
        //执行成功
        message.setText(BotCMDUtil.PERMISSIONS_SUCCESS);
        send(botId,message);

        //删除消有违禁词的被回复消息
        send(botId, DeleteMessage.builder().chatId(msg.getChatId()).messageId(msg.getReplyToMessage().getMessageId()).build());
    }
    
    
    /**
     * 格式 /addblocklist 违禁词1,违禁词2
     * @param chat
     * @param botId
     * @param text
     */
    private void addBlockList(Chat chat, String botId, String text) {
        String[] split = text.split(" ");
        //判断格式是否正确
        if(split.length!=2){
            send(botId,SendMessage.builder().chatId(chat.getId()).text("添加格式如下：\n"+BotCMDUtil.CMD_BLACKLIST+" 违禁词1,违禁词2").build());
        }
    }
    
    /**
     * 发送设置
     * @param chat
     * @param botId
     */
    @Override
    public void start(Chat chat, String botId, String text) {
        if(StringUtils.isEmpty(text)){
            text = sysConfigService.selectConfigByKey("bot.message.start");
        }
        SendMessage message = SendMessage.builder().chatId(chat.getId()).text(text).build();
        JSONObject object = new JSONObject();
        object.put("chatId",chat.getId());
        object.put("timestamp",System.currentTimeMillis());
        List<InlineKeyboardRow> keyboard = new ArrayList<>();
        InlineKeyboardRow buttons = new InlineKeyboardRow();
        InlineKeyboardButton btn = new InlineKeyboardButton("群管系统");
        BotInfo botInfo = botInfoService.selectBotInfoById(Long.valueOf(botId));
        btn.setUrl(BotCommonEnums.BOT_BASE_API + botInfo.getBotName() + "/" + botInfo.getBotApp() + "?startapp=" + Base64.encode(object.toJSONString().getBytes()));
        buttons.add(btn);
        keyboard.add(buttons);
        message.setReplyMarkup(InlineKeyboardMarkup.builder().keyboard(keyboard).build());
        send(botId,message);
        //同步群组信息
        botGroupService.updateTelegramGroup(botId,chat);
    }
    
    /**
     * 发送设置
     * @param chat
     * @param botId
     */
    public void startPrivate(Chat chat, String botId,String text) {
        if(StringUtils.isEmpty(text)){
            text = sysConfigService.selectConfigByKey("bot.message.start");
        }

        List<InlineKeyboardRow> keyboard = new ArrayList<>();
        InlineKeyboardRow row = new InlineKeyboardRow();
        InlineKeyboardButton btn = new InlineKeyboardButton("邀请入群");
        BotInfo botInfo = botInfoService.selectBotInfoById(Long.valueOf(botId));
        btn.setUrl(BotCommonEnums.BOT_BASE_API + botInfo.getBotName()+ "?startgroup=botstart");
        row.add(btn);
        keyboard.add(row);
        send(botId,SendMessage.builder()
                .chatId(chat.getId())
                .text(text)
                .replyMarkup(InlineKeyboardMarkup.builder().keyboard(keyboard).build())
                .build());
        //同步群组信息
        botGroupService.updateTelegramGroup(botId,chat);
    }
}
